package downloader

import (
	"context"
	"errors"
	"fmt"
	"gitee.com/Luna-CY/hui-hui/internal/logger"
	"gitee.com/Luna-CY/hui-hui/internal/util/goroutine"
	"github.com/google/uuid"
	"net/http"
	url2 "net/url"
	"path"
	"time"
)

// Start 启动下载任务
func (cls *Downloader) Start(url string, target TaskTarget, savePath []string, timeout time.Duration) (*Task, error) {
	logger.GetLogger().Sugar().Infof("下载器: 文件下载请求: %s", url)

	var response, err = http.Head(url)
	if nil != err {
		return nil, err
	}

	defer func() {
		_ = response.Body.Close()
	}()

	if 200 != response.StatusCode {
		return nil, fmt.Errorf("请求远程文件失败，错误码: %d，错误信息: %s", response.StatusCode, response.Status)
	}

	u, err := url2.Parse(url)
	if nil != err {
		return nil, err
	}

	var task = new(Task)
	task.Id = uuid.New().String()
	task.State = TaskStateDownloading
	task.Message = "文件下载中"

	task.StartTime = time.Now()
	task.Filename = path.Base(u.Path)
	task.FileSize = response.ContentLength
	task.RemoteAddress = url
	task.Target = target
	task.SavePath = savePath
	task.Timeout = timeout

	task.ctx, task.cancel = context.WithCancel(context.Background())

	cls.mutex.Lock()
	defer cls.mutex.Unlock()

	if cls.quit {
		return nil, errors.New("下载器已退出，无法添加新的下载任务")
	}

	cls.tasks[task.Id] = task

	logger.GetLogger().Sugar().Infof("下载器: 文件下载开始: %s", url)
	goroutine.Go(func() {
		cls.started(task)
	})

	return task, nil
}
